package com.settlement.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.settlement.system.common.result.Result;
import com.settlement.system.model.entity.SysAmazon;
import com.settlement.system.model.vo.SmsVo;
import com.settlement.system.service.SysAmazonService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/v1/sms")
@RequiredArgsConstructor
public class SmsController {

    private final static Logger logger = LoggerFactory.getLogger(SmsController.class);

    private static final ConcurrentHashMap<String, String> SMS_CODE_MAP = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, LocalDateTime> SMS_TIME_MAP = new ConcurrentHashMap<>();

    private final SysAmazonService amazonService;

    @Operation(summary = "通过手机号码获取短信内容")
    @GetMapping("/info/{phone}")
    public String info(@Parameter(description = "手机号码") @PathVariable String phone) {
        String text = SMS_CODE_MAP.get(phone);
        logger.info("phone number：{}，text：{}", phone, text);
        return text;
    }

    @Operation(summary = "保存手机号码获取短信内容")
    @PostMapping("/save")
    public Result<String> save(@RequestBody @Valid SmsVo smsVo) {
        logger.info("save activationId：{}，text：{}", smsVo.getActivationId(), smsVo.getText());
        logger.info("sms：{}", smsVo);
        List<SysAmazon> sysAmazonList = amazonService.list(new LambdaQueryWrapper<SysAmazon>().eq(SysAmazon::getActivationId, smsVo.getActivationId()));
        if (sysAmazonList.size() > 0) {
            SMS_CODE_MAP.put(sysAmazonList.get(0).getPhone(), smsVo.getCode());
            SMS_TIME_MAP.put(sysAmazonList.get(0).getPhone(), LocalDateTime.now());
        }
        LocalDateTime now = LocalDateTime.now();
        // 移除超期的数据
        for (String phone : SMS_TIME_MAP.keySet()) {
            // 超期时间5分钟，移除
            if (now.isAfter(SMS_TIME_MAP.get(phone).plusMinutes(5))) {
                SMS_CODE_MAP.remove(phone);
                SMS_TIME_MAP.remove(phone);
            }
        }
        return Result.success();
    }
}
